package cn.ljy.uem.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.ljy.authority.config.security.UserUtil;
import cn.ljy.authority.config.upload.FileUploadConfig;
import cn.ljy.authority.model.SysUser;
import cn.ljy.authority.service.impl.IBaseService;
import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.common.exception.model.MyWebException;
import cn.ljy.common.utils.file.MyFileModel;
import cn.ljy.common.utils.requests.RequestUtil;
import cn.ljy.uem.dao.SchoolCourseResourceMapper;
import cn.ljy.uem.dao.SchoolCourseSectionResourceMapper;
import cn.ljy.uem.dao.SchoolTeacherMapper;
import cn.ljy.uem.model.SchoolCourseResource;
import cn.ljy.uem.model.SchoolCourseSectionResource;
import cn.ljy.uem.model.SchoolTeacher;
import cn.ljy.uem.model.query.SchoolCourseResourceQuery;
import cn.ljy.uem.service.SchoolCourseResourceService;
import cn.ljy.uem.service.common.CommonSchoolService;
import cn.ljy.uem.utils.file.UemFileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * 课程资源模块实现类
 * 课程资源应该是只有拥有该课程或相应教学任务管理权限的老师才能操作
 * @author 小锋
 * @date 2022/08/17
 * ljy 20221020最后修改
 */
@Service
@Slf4j
public class ISchoolCourseResourceService extends IBaseService<SchoolCourseResource, SchoolCourseResourceQuery> implements SchoolCourseResourceService {

    @Autowired
    private SchoolCourseResourceMapper mapper;

    @Autowired
    private SchoolCourseSectionResourceMapper schoolCourseSectionResourceMapper;
    @Autowired
    private SchoolTeacherMapper schoolTeacherMapper;
    @Autowired
    private CommonSchoolService commonSchoolService;
    @Autowired
    private FileUploadConfig fileUploadConfig;
    @Autowired
    private UemFileUploadUtil uemFileUploadUtil;


    /**
     * 用于检查是否有操作权限
     * 说明：
     * 用于检查是否有资源的操作权限
     */
    private void validateOperatorAuthority(Serializable id){
        //获取原来的资源信息
        SchoolCourseResource schoolCourseResourceOfOrign=mapper.findById(id);
        if(schoolCourseResourceOfOrign!=null){
            //验证当前登录账户是否有该课程的权限
            commonSchoolService.validateCourseManageAuthorityOfLoginTeacher(schoolCourseResourceOfOrign.getCourseId());
        }else{
            throw new MyServiceException("操作失败：该课程资源不存在");
        }
    }

    /**
     * 获取资源的访问网址
     * @param schoolCourseResource
     * @return
     */
    private void initWebUrl(SchoolCourseResource schoolCourseResource){
        if(schoolCourseResource!=null){
            //如果有相对路径，则加上项目网址
            String fileUrl=schoolCourseResource.getFileUrl();
            if(StringUtils.hasLength(fileUrl)){
                schoolCourseResource.setFileUrl(RequestUtil.getBasePath()+fileUrl);
            }
        }
    }

    @Override
    protected void beforeGet(Serializable id) {
        validateOperatorAuthority(id);
    }

    @Override
    protected void beforeUpdate(SchoolCourseResource schoolCourseResource) {
        //验证是否有资源的操作权限
        validateOperatorAuthority(schoolCourseResource.getId());
        //设置最后编辑资源的教师账号
        SysUser sysUser = UserUtil.getLoginUser();//获取当前登录信息
        SchoolTeacher editor = schoolTeacherMapper.getTeacherByUserId(sysUser.getId());//获取当前登录账户对应的教师信息
        schoolCourseResource.setEditor(editor.getId());
    }

    @Override
    protected void beforeSave(SchoolCourseResource schoolCourseResource) {
        //验证是否有该课程的管理权限
        //验证当前登录账户是否有该课程的权限
        commonSchoolService.validateCourseManageAuthorityOfLoginTeacher(schoolCourseResource.getCourseId());
        //设置发布资源的教师账号
        SysUser sysUser = UserUtil.getLoginUser();//获取当前登录信息
        SchoolTeacher creator = schoolTeacherMapper.getTeacherByUserId(sysUser.getId());//获取当前登录账户对应的教师信息
        schoolCourseResource.setCreator(creator.getId());
        //如果前端没有传递作者信息，则默认是当前发布教师的姓名
        if(!StringUtils.hasLength(schoolCourseResource.getAuthor())){
            schoolCourseResource.setAuthor(creator.getName());//发布资源的教师姓名
        }
        //补全参数,也可以选择在Mybatis用动态sql实现默认值的处理
        if (schoolCourseResource.getType()==null){
            schoolCourseResource.setType(2);
        }
        if(schoolCourseResource.getClick()==null){
            schoolCourseResource.setClick(0);
        }
        if(schoolCourseResource.getSort()==null){
            schoolCourseResource.setSort(0);
        }
        if(schoolCourseResource.getRecommend()==null){
            schoolCourseResource.setRecommend(false);
        }
        if(schoolCourseResource.getAllowDownload()==null){
            schoolCourseResource.setAllowDownload(false);
        }
        if(schoolCourseResource.getDownloadNumber()==null){
            schoolCourseResource.setDownloadNumber(0);
        }
        if(schoolCourseResource.getRecycle()==null){
            schoolCourseResource.setRecycle(false);
        }

    }

    @Override
    protected void beforeDelete(Serializable[] ids) {
        for(Serializable id:ids){
            //验证是否有该课程的管理权限
            validateOperatorAuthority(id);
        }
    }

    /**
     * 重写资源删除功能
     * 1.先批量删除数据库中的资源
     * 2.再批量删除资源文件
     * @param ids 多个对象的主键集合
     */
    @Override
    public void delete(@NotEmpty(message = "操作失败：请选择要移除的记录") Serializable[] ids) {
        //1.获取对应的资源集合
        List<SchoolCourseResource> schoolCourseResources=mapper.findByIdIn(ids);
        //2.删除数据库中的资源对象
        //(2)删除课程章节与资源的关系集合
        schoolCourseSectionResourceMapper.deleteByResourceIds(ids);
        //（1）删除课程资源
        super.delete(ids);
        //3.删除服务器上的资源文件
        for(SchoolCourseResource schoolCourseResourceOfEach:schoolCourseResources){
            //获取资源相对文件路径。因为后面设计绝对路径可以随时变动，例如从c盘切换到d盘
            String fileUrl=schoolCourseResourceOfEach.getFilePath();
            //计算出资源当前保存的绝对路径
            String filePath=fileUploadConfig.getResourceUploadBasePath()+fileUrl;
//            log.info(filePath);
            //删除文件
            FileUtil.del(filePath);
        }
    }

    @Override
    protected void afterFindAll(List<SchoolCourseResource> list) {
        for(SchoolCourseResource schoolCourseResource:list){
            this.initWebUrl(schoolCourseResource);
        }
    }

    /**
     * 通过章节id查找资源
     */
    @Override
    public List<SchoolCourseResource> GetAllCourseResourceBySectionId(String SectionId) {
        List<SchoolCourseResource> schoolCourseResources=new ArrayList<>();
        if(StringUtils.hasLength(SectionId)){
            //相对应资源关系表
            List<SchoolCourseSectionResource> schoolCourseSectionResources= schoolCourseSectionResourceMapper.getResourceBySectionId(SectionId);
            if(!schoolCourseSectionResources.isEmpty()){
                //遍历资源合集
                for (SchoolCourseSectionResource schoolCourseSectionResource:schoolCourseSectionResources){
                    //查找各自id的资源
                    SchoolCourseResource schoolCourseResource = mapper.findById(schoolCourseSectionResource.getResourceId());
                    schoolCourseResource.setSectionResourceId(schoolCourseSectionResource.getId());
                    schoolCourseResources.add(schoolCourseResource);
//                    System.out.println(schoolCourseSectionResource.getId());
                }
            }else {
                throw new MyWebException("该章节并无资源");
            }
        }else {
            throw new MyWebException("章节id为空,请输入章节id");
        }

        return schoolCourseResources;
    }

    @Override
    public SchoolCourseResource uploadResource(Long courseId, MultipartFile file) {
        //1.验证是否有该课程的管理权限
        //验证当前登录账户是否有该课程的权限
        commonSchoolService.validateCourseManageAuthorityOfLoginTeacher(courseId);
        //1.上传资源，并将资源上传后的网址返回
        MyFileModel myFileModel=uemFileUploadUtil.uploadResource(file);
        //2.将上传的资源存进数据库X
        SchoolCourseResource schoolCourseResource=new SchoolCourseResource();
        schoolCourseResource.setTitle(file.getOriginalFilename()); //获取上传的文件名作为资源名
        schoolCourseResource.setCourseId(courseId); //设置课程id
        schoolCourseResource.setFileUrl(myFileModel.getFileRelativeUrl());//访问资源的相对路径
        schoolCourseResource.setFilePath(myFileModel.getFileRelativePath()); //文件保存的相对物理路径
        schoolCourseResource.setResourceSize(file.getSize());//文件大小
        //存入数据库
        try {
            //如果存储资源出错
            super.save(schoolCourseResource);
        } catch (Exception e) {
            //删除已经上传的文件
            FileUtil.del(myFileModel.getFilePath());
            throw new MyServiceException(e.getMessage());
        }
        return schoolCourseResource;
    }

}
